/* GSExcelToManufacture.java
 *
 * Project/Product: APEP-JZCG
 *
 * Modify Information:
 * =============================================================================
 *   Author	Date       Description
 *   ----------	---------- ---------------------------------------------------
 *   peng.ning	2008-10-24	First release
 *
 * Licensed Materials - Property of APEP
 * =============================================================================
 *    (C) COPYRIGHT Shanghai Auto Mart E-Procurement Co., Ltd. 2007 - 2008
 *    All Rights Reserved.
 *
 *    This software is the confidential and proprietary information of
 *    Shanghai Auto Mart E-Procurement Co., Ltd. ("Confidential Information").
 *    You shall not disclose such Confidential Information and shall use it only
 *    in accordance with the terms of the license agreement you entered into 
 *    with Shanghai Auto Mart E-Procurement Co., Ltd.
 *
 * Noties:
 * =============================================================================
 * 
 */

package com.hitrust.gs.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

import org.apache.struts.upload.FormFile;

import com.hitrust.gs.bean.GSManufactureBean;
import com.hitrust.gs.bean.GSManufactureCategoryBean;
import com.hitrust.gs.bean.GSProviderBean;
import com.hitrust.gs.business.GSManufactureCategoryProcessor;
import com.hitrust.gs.business.GSManufactureProcessor;
import com.hitrust.gs.business.GSProviderProcessor;
import com.hitrust.gs.dao.GSManufactureDAO;
import com.hitrust.gs.form.GSImportExcelForm;
import com.hitrust.gs.lib.GSBaseConstants;
import com.hitrust.gs.lib.GSLogWriter;
import com.hitrust.gs.service.GSBaseAction;
import com.hitrust.gs.service.GSBaseForm;
import com.hitrust.gs.util.RegulaUtil;
import com.hitrust.gs.util.exception.GSException;
import com.hitrust.gs.util.page.ResultProcess;
import com.hitrust.gs.vo.GSTemporaryManufactureView;

public class GSExcelToManufactureInSteadOfTemporary extends GSBaseAction {

    /*
     * (non-Javadoc)
     * 
     * @see com.apep.jzcg.service.GSBaseAction#execute(com.apep.jzcg.service.GSBaseForm)
     */

    public static final String SHEET_NAME = "产品信息";
    public static final String SEP = "%";
    public static String[] HEAD_NAMES = { "序号", "集中编码","替换的14位集中编码"};
    public static String[] HEAD_NAMES_PRICE = { "序号",  "集中编码", "替换的14位集中编码" };
    public boolean[] COL_CHECK = new boolean[4];
    public boolean[] COL_CHECK_PRICE = new boolean[4];
    public GSTemporaryManufactureView manuview = null;
    GSProviderProcessor ppro = new GSProviderProcessor();
    GSManufactureCategoryProcessor mcpro = new GSManufactureCategoryProcessor();
    public static final String zhibao = "^\\d+$";
    public static final String regula = "[^'\"<>&]*";
    
    public String execute(GSBaseForm aForm) throws Exception {
        GSImportExcelForm tGSImportExcelForm = (GSImportExcelForm) aForm;
        FormFile formFile = tGSImportExcelForm.getExcelfile();
        tGSImportExcelForm.getRequest().setAttribute("target", "_self");
        Object modify = aForm.getSession().getAttribute("modify");
        if(modify!=null&&modify.toString().equals("true")){
            tGSImportExcelForm.getRequest().setAttribute("action", "A400337.do");
        }else
           tGSImportExcelForm.getRequest().setAttribute("action", "A400313.do");
        if (formFile!=null) {
            ArrayList tList = loadDataFromExcel(formFile.getInputStream());
            ResultProcess tProc = new ResultProcess();
            tProc.setResult(tList);
            if(GSBaseConstants.PLANPRICE.equals("true")){
                aForm.getRequest().setAttribute("isPlanprice", "1");
            }else{
                aForm.getRequest().setAttribute("isPlanprice", "0");
            }
            aForm.getSession().setAttribute("manufactureExcel", tProc);
        }
        return GSBaseConstants.FORWARD_SUCCESS;
    }

    /**
     * 从Excel中载入格式化数据，数据项之间以分隔符%隔开
     * 
     * @param aInputStream
     * @param aPage
     * @param aPageSize
     * @return
     * @throws Exception
     */
    public ArrayList loadDataFromExcel(InputStream aInputStream) throws Exception {

        ArrayList tPageDataList = new ArrayList();
        Workbook tExcelWorkbook = null;

        try {
            tExcelWorkbook = Workbook.getWorkbook(aInputStream);

            Sheet tExcelSheet = tExcelWorkbook.getSheet(SHEET_NAME);
            if (tExcelSheet == null) {
                throw new GSException("批量导入产品失败:文件格式不正确,无法找到：" + SHEET_NAME);
            }
            for (int i = 1; i < tExcelSheet.getRows(); i++) {
                Cell tCells[] = tExcelSheet.getRow(i);
                String tRowText = "";
                int num = tCells.length;
                for (short j = 0; j < num; j++) {
                    Cell tExcelCell = tCells[j];
                    if (tExcelCell == null) {
                        break;
                    }
                    String tCellValue = tExcelCell.getContents();
                    if (tCellValue.length() == 0) {
                        tCellValue = " ";
                    }
                    tRowText += tCellValue + SEP;
                }
                if(GSBaseConstants.PLANPRICE.equals("true")){
                    for (int a = num; a < HEAD_NAMES_PRICE.length; a++) {
                        tRowText += " " + SEP;
                    }
                }else{
                    for (int a = num; a < HEAD_NAMES.length; a++) {
                        tRowText += " " + SEP;
                    }
                }

                // 检查数据是否正确,如果和数据库中不符则将结果添加到末尾,从第二行开始
                tRowText = this.checkManufacture(tRowText,i-1);
                for (int tJ = 0; tJ < COL_CHECK.length; tJ++) {
                    if (COL_CHECK[tJ] == false) {
                        throw new GSException(tRowText);
                    }
                }
                

                tPageDataList.add(manuview);
                GSLogWriter.info(tRowText);
            }
        } catch (BiffException e) {
            GSLogWriter.error(e.getMessage());
            throw new GSException("批量导入产品明细失败:文件格式不正确！");
        } catch (IOException e) {
            GSLogWriter.error(e.getMessage());
            throw new GSException("批量导入产品明细失败:文件格式不正确！");
        } finally {
            if (tExcelWorkbook != null)
                tExcelWorkbook.close();
        }
        return tPageDataList;
    }
     
    public String checkManufacture(String aRowText,int a) throws GSException {
        manuview = new GSTemporaryManufactureView();
        for (int i = 0; i < COL_CHECK.length; i++) {
            COL_CHECK[i] = true;
        }
        try {
            String[] tRecorderColumns = aRowText.split(SEP);
            for (int i = 0; i < tRecorderColumns.length; i++) {
            	if(!RegulaUtil.matchByString(tRecorderColumns[i],regula )){
            		 COL_CHECK[i] = false;
                     return HEAD_NAMES[0] + tRecorderColumns[0] + ": " + HEAD_NAMES[i] + "中不能有',\",<,>,&等特殊字符!";
            	}
			}
            manuview.setGs_manufacture_id(tRecorderColumns[0].trim());
            if ("".equals(tRecorderColumns[1].trim())||tRecorderColumns[1].trim().length()!=13) {
                COL_CHECK[2] = false;
                return HEAD_NAMES[0] +tRecorderColumns[0]+ ": " + tRecorderColumns[1] + ": " + HEAD_NAMES[1] + "不能为空或集中编码长度不为13!";
            } else {
                manuview.setGs_concentricity_id(tRecorderColumns[1].trim());
            }
            if ("".equals(tRecorderColumns[2].trim())||tRecorderColumns[2].trim().length()!=14) {
                COL_CHECK[3] = false;
                return HEAD_NAMES[0] +tRecorderColumns[0]+ ":" + tRecorderColumns[2] + ": " + HEAD_NAMES[2] + "不能为空或被替换编码长度不为14!";
            } else {
                manuview.setGs_temporary_concentricity_id(tRecorderColumns[2].trim());
            }
            
            GSManufactureProcessor processor = new GSManufactureProcessor();
            GSManufactureBean cBean = processor.getManufInfoByConcentricityId(tRecorderColumns[1].trim());
            if(cBean==null){
            	 COL_CHECK[2] = false;
                 return HEAD_NAMES[0]+ tRecorderColumns[1] + ": " + HEAD_NAMES[1] + ",13位产品编码不存在!";
            }
            GSManufactureBean tempbean = processor.getManufInfoByConcentricityId(tRecorderColumns[2].trim());
            if (tempbean==null) {
                COL_CHECK[2] = false;
                return HEAD_NAMES[0] + tRecorderColumns[2] +": " + HEAD_NAMES[2] + ",14位产品不存在!";
            }
            GSProviderBean pbean = ppro.queryProviderByShortNameOrId(tempbean.getGs_provider_id().trim());
            if (pbean == null) {
                COL_CHECK[1] = false;
                return HEAD_NAMES[0] +tRecorderColumns[0] + ": " + HEAD_NAMES[2] + ",不存在或有相同的供应商!";
            }else if(!cBean.getGs_provider_id().equals(tempbean.getGs_provider_id())){
                COL_CHECK[1] = false;
                return tRecorderColumns[1]+"的供应商和" +tRecorderColumns[2] +"的供应商不相同";
            } else {
                manuview.setGs_provider_id(pbean.getGs_provider_id());
                manuview.setGs_provider_shortname(pbean.getGs_provider_shortname());
            }
            manuview.setIs_buy(cBean.getIs_buy().trim());
            manuview.setGs_balance_mode(cBean.getGs_balance_mode().trim());
 
            manuview.setGs_manufacture_unitprice(cBean.getGs_manufacture_unitprice());
            manuview.setGs_quant_unit(cBean.getGs_quant_unit().trim());
            
            GSManufactureCategoryBean mcbean = mcpro.queryManufactureCatetoryByIdOrName(cBean.getGs_manufacture_category_id().trim());
            if (mcbean == null) {
                COL_CHECK[1] = false;
                return HEAD_NAMES[0] + tRecorderColumns[0] + ": " + HEAD_NAMES[1] + "其产品分类不存在或有相同类型名称！";
            } else {
                manuview.setGs_manufacture_category_id(mcbean.getGs_manufacture_category_id());
                manuview.setGs_manufacture_category_name(mcbean.getGs_manufacture_category_name());
            }
            manuview.setGs_manufacture_name(cBean.getGs_manufacture_name().trim());
            manuview.setGs_manufacture_type(cBean.getGs_manufacture_type().trim());
            manuview.setGs_manufacture_spec(cBean.getGs_manufacture_spec().trim());
            if(!RegulaUtil.matchByString(cBean.getGs_quality_assure_period().trim(),zhibao)&&!cBean.getGs_quality_assure_period().trim().equals("")){
       		 	COL_CHECK[12] = false;
                return HEAD_NAMES[0] + tRecorderColumns[0] + ": " + HEAD_NAMES[1] + "只能为0或者正整数，默认单位为天!";
            }
            manuview.setGs_quality_assure_period(cBean.getGs_quality_assure_period().trim());
            manuview.setGs_make_area(cBean.getGs_make_area().trim());
            manuview.setGs_manufacture_brand(cBean.getGs_manufacture_brand().trim());
            manuview.setGs_drawing_piece_code(cBean.getGs_drawing_peice_code().trim());
            String temp = "";
            manuview.setGs_appender_property(temp);
            manuview.setGs_remark(cBean.getGs_remark().trim());
            manuview.setGs_recorder_id(String.valueOf(a));//对象编号
            manuview.setNumber(tRecorderColumns[0]);
        } catch (GSException e) {
            e.printStackTrace();
            GSLogWriter.error(e.getMessage());
            throw new GSException("批量导入产品明细失败:" + e.getLocalizedMessage());

        }
        return aRowText + "匹配成功！";
    }
}
